<template>
    <div class="adminUser-page">
      <!-- 添加管理员、批量删除管理员部分 -->
      <div class="page-btns">
        <el-button type="primary" icon="plus" @click="editOrSaveUserInfo(null)">添加管理员</el-button>
        <el-button type="warning" icon="delete" :disabled="deleteBtnState" @click="deleteUserList">批量删除管理员</el-button>
      </div>
      <!-- 管理员数据列表部分 -->
      <el-table :data="userList" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="password" label="用户密码" />
        <el-table-column prop="nickname" label="用户昵称" />
        <el-table-column prop="email" label="用户邮箱" />
        <el-table-column prop="phone" label="用户手机" />
        <el-table-column prop="avatar" align="center" label="用户头像">
          <template #="{row,$index}">
            <img :src="row.avatar" alt="用户头像" style="width:60px;height:60px;">
          </template>
        </el-table-column>
        <el-table-column prop="role" label="用户角色" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column label="操作" width="130" align="center">
          <template #="{row,$index}">
            <el-button type="primary" plain :icon="Edit" @click="editOrSaveUserInfo(row)" />
            <el-popconfirm :icon="InfoFilled" icon-color="#626AEF" cancel-button-text="取消" confirm-button-text="确定" title="确定删除该用户吗?" @confirm="deleteUser(row)">
              <template #reference>
                <el-button type="success" plain :icon="Delete" @click="" />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- drawer_dialog抽屉部分 -->
      <el-drawer ref="drawerRef" v-model="drawer_dialog" v-if="drawer_dialog" :title="drawerState === 0 ? '添加管理员用户' : '修改管理员用户'" :before-close="handleClose" direction="rtl" class="drawerDialog">
        <div class="drawerDialog_content">
          <el-form :model="userInfo" :rules="rules" ref="userInfoForms">
            <el-form-item label="用户名" prop="username" required label-width="80px">
              <el-input v-model="userInfo.username" autocomplete="off" />
            </el-form-item>
            <el-form-item label="用户密码" prop="password" required label-width="80px">
              <el-input v-model="userInfo.password" autocomplete="off" show-password />
            </el-form-item>
            <el-form-item label="用户昵称" label-width="80px">
              <el-input v-model="userInfo.nickname" autocomplete="off" />
            </el-form-item>
            <el-form-item label="用户邮箱" label-width="80px">
              <el-input v-model="userInfo.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="用户手机" label-width="80px">
              <el-input v-model="userInfo.phone" autocomplete="off" />
            </el-form-item>
            <el-form-item label="用户头像" label-width="80px">
              <el-upload class="avatar-uploader" :action="uploadServer" name="multipartFile" :before-upload="handleBeforeUpload" :on-success="handleUploadSuccess" :show-file-list="false" :limit="1">
                <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="用户角色" prop="role" required label-width="80px">
              <el-input v-model="userInfo.role" autocomplete="off" />
            </el-form-item>
          </el-form>
          <div class="drawerDialog_btns">
            <el-button @click="cancel_btn">取消</el-button>
            <el-button type="primary" :loading="loading" @click="updateOrSaveUser_btn">提交</el-button>
          </div>
        </div>
      </el-drawer>
    </div>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted } from "vue";
//引入Element-plus
import { ElTable, ElTableColumn, ElButton, ElDrawer, ElForm, ElFormItem, ElInput, ElUpload ,ElIcon, ElMessage, ElMessageBox, ElPopconfirm } from "element-plus";
import { Delete, Edit, Plus, InfoFilled } from '@element-plus/icons-vue';
//引入请求函数
import { reqUserInfoList, reqSaveUser, reqUpdateUser, reqDelUser } from "@/api/user/index.ts";

//后台管理员用户列表
let userList = ref([]);
const drawer_dialog = ref(false);
const loading = ref(false);  //提交按钮的loadding控制
const deleteBtnState = ref(true);  //批量删除用户的按钮状态
//drawer抽屉dialog实例
const drawerRef = ref<InstanceType<typeof ElDrawer>>();
//drawer抽屉状态:修改用户信息 添加管理员用户
let drawerState = ref(0);  //0:添加管理员 1:修改管理员
//表单收集的用户信息
let userInfo = reactive({
  id:'',
  username:'',
  password:'',
  nickname:'',
  email:'',
  phone:'',
  avatar:'',
  role:'',
  createTime:'',
  updateTime:''
})
//用户信息表单组件实例
const userInfoForms = ref();
//文件上传的服务器地址
const uploadServer = "http://127.0.0.1:8090/uploadByBlob";
//table复选框选择的要批量删除的管理员用户
let delUserInfoList = ref([]);


//表单校验
const validateUsername = (rule: any, value: any, callback: any) => {
  if (value === '' || value.length < 4) {
    callback(new Error('请输入合法的用户名'))
  } else {
    callback();
  }
}
const validatePassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else if (value.length < 4){
    callback(new Error('密码长度不能少于四位'));
  } else {
    callback();
  }
}
const validateRole = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入用户角色'))
  } else if (!(value === 'supperAdmin' || value === 'admin')){
    callback(new Error('请输入合法的用户角色,如:supperAdmin或admin'));
  } else {
    callback();
  }
}
const rules = reactive({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }],
  role: [{ validator: validateRole, trigger: 'blur' }]
})

//获取后台管理员所有用户数据
const getAdminUserList = async () => {
  let res = await reqUserInfoList();
  if(res.code === 200){
    let responseData = res.data;
    //处理用户密码 --> 123456 -> base64编码
    responseData.forEach(item => {
      item.password = btoa(item.password.toString());
    });
    userList.value = responseData;
    ElMessage({type:"success",message:"管理员数据获取成功!"});
  }
  console.log('查询后台管理员所有数据api',res);
}
//添加一个后台管理员用户请求
const addUser = async () => {
  //对请求参数进行整理
  const user = JSON.parse(JSON.stringify(userInfo));
  for(let key in user){
    if(user[key] === ''){
      delete user[key];
    }
  }
  if(!(user.username && user.role && user.password)){
    ElMessage({type:"info",message:"用户名或用户角色或用户密码未填写完整!"});
    return false;
  }
  //发送请求
  let res = await reqSaveUser(user);
  if(res.code === 200){
    //消息提示
    ElMessage({type:'success', message:"用户添加成功!"});
  } else {
    ElMessage({type:"error", message:"用户添加失败!"});
    return false;
  }
  console.log('添加管理员用户api',res);
  return true;
}
//修改一个后台管理员用户
const updateUser = async () => {
  //对请求参数进行整理
  const user = JSON.parse(JSON.stringify(userInfo));
  //清楚参数为空的参数
  for(let key in user){
    if(user[key] === ''){
      delete user[key];
    }
  }
  if(!(user.id && user.username && user.password)) return false;
  //发送请求
  let res = await reqUpdateUser(user);
  if(res.code === 200){
    //消息提示
    ElMessage({type:'success', message:"用户修改成功!"});
  } else {
    ElMessage({type:"error", message:res.msg});
    return false;
  }
  console.log('修改管理员用户api',res);
  return true;
}
//table表格的复选框change事件
const handleSelectionChange = (value:any) => {
  if(value.length !== 0){
    deleteBtnState.value = false;
    delUserInfoList.value = value;
  } else {
    deleteBtnState.value = true;
    delUserInfoList.value = [];
  }
}
//删除一个后台管理员用户
const deleteUser = async (userInfo:any) => {
  let usernameList = [];
  usernameList.push(userInfo.username);
  let res = await reqDelUser(usernameList);
  if(res.code === 200) {
    //删除成功
    ElMessage({type:'success',message:"用户删除成功!"});
  } else {
    //删除失败
    ElMessage({type:"error",message:res.msg});
  }
  console.log('删除后台管理员api',res);
  //重新请求管理员列表数据
  getAdminUserList();
}
//批量删除后台管理员用户
const deleteUserList = async () => {
  if(delUserInfoList.value.length === 0) return;
  let delUsernameList = delUserInfoList.value.map(item => {
    return item.username;
  })

  ElMessageBox.confirm('确定要删除选中的管理员用户吗?','提示',{confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning',}).then(async() => {
    let res = await reqDelUser(delUsernameList);
    if(res.code === 200) {
      //删除成功
      ElMessage({type:'success',message:"用户删除成功!"});
    } else {
      //删除失败
      ElMessage({type:"error",message:res.msg});
    }
    console.log('批量删除后台管理员api',res);
    //重新请求管理员列表数据
    getAdminUserList();
  }).catch(() => {
    ElMessage({type: 'info',message: '取消删除!'});
  }) 
}

//编辑或添加管理员用户的dialog开关
const editOrSaveUserInfo = (user:any = null) => {
  //打开drawerDialog开关
  if(user !== null) {
    drawerState.value = 1;
  } else {
    drawerState.value = 0;
  }
  drawer_dialog.value = true;

  //获取用户信息 
  if(user !== null){
    userInfo.id = user.id;
    userInfo.username = user.username;
    userInfo.password = user.password;
    userInfo.nickname = user.nickname;
    userInfo.email = user.email;
    userInfo.phone = user.phone;
    userInfo.avatar = user.avatar;
    userInfo.role = user.role;
    userInfo.createTime = '';
    userInfo.updateTime = '';
    //避免浏览器缓存图片地址，地址上添加时间戳请求参数
    //const timestamp = new Date().getTime();
    //userInfo.avatar = userInfo.avatar + "?t=" + timestamp;
    //将base64编码的密码---> 数字  MTIzNDU2--->123456
    userInfo.password = atob(userInfo.password);
  }
}

//文件上传前的回调
const handleBeforeUpload = (file:any) => {
  if(!(file.type === 'image/jpeg' || file.type === 'image/png')){
    ElMessage({type:"info",message:"请选择jpg/png类型的图片文件!"});
    return false;
  }
  if((file.size)/1024/1024 > 4){
    ElMessage({type:"info",message:"请选择小于4M的图片文件"});
    return false;
  }
  return true;
}
//头像上传成功的回调
const handleUploadSuccess = (response:any, uploadFile:any) => {
  userInfo.avatar = response.data[0];
  console.log('文件上传api',response);
}

//dialog关闭之前
const handleClose = (done?:any) => {
  drawer_dialog.value = false;
  loading.value = false;
  //清空数据
  userInfo.id = '';
  userInfo.username = '';
  userInfo.password = '';
  userInfo.nickname = '';
  userInfo.email = '';
  userInfo.phone = '';
  userInfo.avatar = '';
  userInfo.role = '';
  userInfo.createTime = '';
  userInfo.updateTime = '';
}
//取消按钮
const cancel_btn = () => {
  handleClose();
}
//提交按钮(修改用户信息或添加用户)
const updateOrSaveUser_btn = async () => {
  //loading效果展示
  loading.value = true;
  //发送请求(判断是添加还是修改)
  if(drawerState.value === 0){
    //添加管理员
    let isAdd = await addUser();
    if(!isAdd)return loading.value = false;
  } else if (drawerState.value === 1) {
    //修改管理员
    let isUpdate = await updateUser();
    if(!isUpdate)return loading.value = false;
  }
  //请求成功将loading置为false
  loading.value = false;
  //关闭drawerDialog抽屉
  handleClose();
  //更新管理员数据列表
  getAdminUserList();
}



//生命周期
onMounted(() => {
  getAdminUserList();
})
</script>

<style lang='scss'>
.adminUser-page {
  width: 100%;
  height: 100%;

  .page-btns {
    margin-bottom: 20px;
  }

  // 头像上传部分样式
  .drawerDialog {
    .drawerDialog_content{
      .avatar-uploader{
        .avatar {
          width: 78px;
          height: 78px;
          display: block;
        } 
        .el-upload{
          border: 1px dashed var(--el-border-color);
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          transition: var(--el-transition-duration-fast);

          .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 78px;
            height: 78px;
            text-align: center;
          }
        }
        .el-upload:hover {
          border-color: var(--el-color-primary);
        }
      }
    }
  }
}
</style>